package com.wowangz.cms.jpush.api;

import java.io.IOException;
import java.rmi.server.ServerCloneException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wowangz.cms.common.utils.MessageObject;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.dailyoperation.store.pojo.StoreRedisInfo;
import com.wowangz.cms.jpush.pojo.Jpush;
import com.wowangz.cms.jpush.service.JpushService;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.autotask.pojo.MQQueueData;
import com.wowangz.cms.syscore.autotask.pojo.StoreLoginUser;
import com.wowangz.cms.syscore.autotask.service.StoreDatabaseResourceService;
import com.wowangz.cms.syscore.pojo.RouteInfo;
import com.wowangz.cms.syscore.service.BaseService;
import com.wowangz.cms.syscore.utils.JedisUtil;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

/**
 * 消息推送
 * 
 * @author Davis
 *
 */
@Controller
@Scope("prototype")
public class JpushController extends BaseController {
	protected static final Logger LOG = LoggerFactory.getLogger(JpushController.class);

	@RequestMapping(value = "/jpush/jspushAdd.web")
	public String jspushAdd() {
		return "/WEB-INF/jsp/jpush/jpushAdd";
	}

	@RequestMapping(value = "/jpush/jspushView.web")
	public String jspushView(HttpServletRequest request, Model model) {
		String id = request.getParameter("id");
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("id", id);
		JpushService jpushService = (JpushService) IssTransactionContainer.getInstance(JpushService.class, false);
		Jpush jpush = jpushService.getJpushInfo(paramsMap);
		model.addAttribute("allpersonname", SysConstant.BoradAllperson.getName(jpush.getAllperson()));
		model.addAttribute("isSingle", SysConstant.IsSingle.getName(Long.valueOf(jpush.getIsSingle())));
		model.addAttribute("jpush", jpush);
		System.out.println("进入推送的添加信息的页面");
		return "/WEB-INF/jsp/jpush/jpushView";
	}

	@RequestMapping(value = "/jpush/sendNotices.json", method = RequestMethod.POST)
	public void send(Jpush jpush, HttpServletRequest request, HttpServletResponse response) {
		MessageObject object = new MessageObject();
		try {
			Set<String> tagsValues = new HashSet<String>();
			String userid = request.getParameter("userid");
			String loginname = request.getParameter("loginname");
			if (StringUtils.isNotEmpty(userid)) {
				StoreLoginUser storeLoginUser = (StoreLoginUser) JedisUtil.getPublicDataObject(loginname,
						StoreLoginUser.class, JedisUtil.STORE_LOGINUSER);
				String alias = storeLoginUser.getAlias();
				tagsValues.add(alias);
			}
			String alias = "";
			for (Iterator<String> iterator = tagsValues.iterator(); iterator.hasNext();) {
				String string = (String) iterator.next();
				alias += string + ",";
			}
			if (jpush.getStoreid() != null) {
				String storeid = String.valueOf(jpush.getStoreid());
				StoreRedisInfo storeRedisInfo = (StoreRedisInfo) JedisUtil.getPublicDataObject(String.valueOf(storeid),
						StoreRedisInfo.class, JedisUtil.STORE_INFO);
				String storename = storeRedisInfo.getStorename();
				jpush.setStorename(storename);
				jpush.setAlias(alias);
				jpush.setUserid(getUserContext().getLoginUser().getId());
				StoreDatabaseResourceService storeDatabaseResourceService = (StoreDatabaseResourceService) IssTransactionContainer
						.getInstance(StoreDatabaseResourceService.class, false);
				Map<String, Object> conditionMap = new HashMap<String, Object>();
				conditionMap.put("storeid", storeid);
				List<RouteInfo> routeInfos = storeDatabaseResourceService.queryStoreDatabaseByStoreID(conditionMap);
				MQQueueData data = null;
				for (RouteInfo routeInfo : routeInfos) {
					data = new MQQueueData();
					data.setStoreid(routeInfo.getStoreid());
					data.setDbip(routeInfo.getIp());
					data.setDbname(routeInfo.getDbname());
					data.setDbpassword(routeInfo.getPassword());
					data.setDbusername(routeInfo.getUsername());
					data.setDbport(routeInfo.getPort());
				}
				jpush.setData(data);
			}
			jpush.setStatusid(SysConstant.RecordStatus.VALID);
			jpush.setResources(SysConstant.SystemResource.DEFAULTTIME);
			BaseService baseService = new BaseService();
			baseService.sendjJpushData(jpush);
			String inforMessage = MessageResourcesUtils.getMessage(request, "jpush.alert.info1");
			object.setInforMessage(inforMessage);
		} catch (Exception e) {
			e.printStackTrace();
			String errorMessage = MessageResourcesUtils.getMessage(request, "jpush.alert.info2");
			object.setErrorMessage(errorMessage);
		} finally {
			try {
				response.getWriter().write(object.getJsonMapper(object));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@RequestMapping(value = "/jpush/queryJpushInfoList.web")
	public String queryJpushInfoList(Model model) {

		return "/WEB-INF/jsp/jpush/jpushList";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/jpush/queryJpushInfoList.json", method = RequestMethod.POST)
	public void queryJpushInfoList(HttpServletRequest request, HttpServletResponse response) {
		DataResult dataResult = new DataResult();
		try {
			PangingParam pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request,
					PangingParam.class);
			Map<String, Object> map = new HashMap<String, Object>();
			map = (Map<String, Object>) ServletUtils.getParametersToHashMap(request);
			DataGrid dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			String name = request.getParameter("name");
			if (StringUtils.isNotEmpty(name)) {
				map.put("name", "%" + name + "%");
			}
			map.put("order", dataGrid.getOrder());
			JpushService jpushService = (JpushService) IssTransactionContainer.getInstance(JpushService.class, false);
			dataResult = jpushService.getDataResult(pangingParam, map);
		} catch (ServerCloneException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@RequestMapping(value = "/jpush/queryStoreUserInfoList.json")
	public void queryStoreUserInfoList(HttpServletRequest request, HttpServletResponse response) {
		String page = request.getParameter("page");// 第几页
		String rows = request.getParameter("rows");// 每页显示的数目
		String storeids = request.getParameter("storeid");
		Long storeid = 0l;
		if (StringUtils.isNotEmpty(storeids)) {
			storeid = Long.parseLong(storeids);
		}
		Map<String, Object> conditionMap = new HashMap<String, Object>();
		StoreDatabaseResourceService storeDatabaseResourceService = (StoreDatabaseResourceService) IssTransactionContainer
				.getInstance(StoreDatabaseResourceService.class, false);
		conditionMap.put("storeid", storeid);
		List<RouteInfo> routeInfos = storeDatabaseResourceService.queryStoreDatabaseByStoreID(conditionMap);
		conditionMap.put("page", page);
		conditionMap.put("rows", rows);
		conditionMap.put("username", request.getParameter("username"));
		String userInfos = "";
		if (routeInfos != null && routeInfos.size() > 0) {
			userInfos = query(routeInfos.get(0), false, conditionMap);
		}
		try {
			response.getWriter().write(userInfos);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String query(RouteInfo routeInfo, boolean flag, Map<String, Object> conditionMap) {
		String userInfos = "";
		Connection conn = null;
		PreparedStatement preparedStatement = null;
		ResultSet rs = null;
		// 商户普通用户同步
		try {
			conn = getConnection(routeInfo);
			if (!conn.isClosed()) {
				String sql = "select * from sys_user "
						+ "where statusid = ? and storeid = ? and checkstatus = ? and username like ? limit ?,?";
				preparedStatement = conn.prepareStatement(sql);
				preparedStatement.setLong(1, SysConstant.RecordStatus.VALID);
				preparedStatement.setLong(2, Long.parseLong(conditionMap.get("storeid").toString()));
				preparedStatement.setLong(3, SysConstant.CheckStatus.CHECKED);
				String page = conditionMap.get("page").toString();// 第几页
				String rows = conditionMap.get("rows").toString();// 每页显示的数目
				preparedStatement.setString(4, conditionMap.get("username").toString());
				preparedStatement.setInt(5, (Integer.parseInt(page) - 1) * Integer.parseInt(rows));
				preparedStatement.setInt(6, Integer.parseInt(page) * Integer.parseInt(rows));
				rs = preparedStatement.executeQuery();
				userInfos = resultSetToJson(rs);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(conn, preparedStatement, null, rs);
		}
		return userInfos;
	}

	public String resultSetToJson(ResultSet rs) throws SQLException, JSONException {
		// json数组
		JSONArray array = new JSONArray();
		// 获取列数
		ResultSetMetaData metaData = rs.getMetaData();
		int columnCount = metaData.getColumnCount();
		// 遍历ResultSet中的每条数据
		while (rs.next()) {
			JSONObject jsonObj = new JSONObject();
			// 遍历每一列
			for (int i = 1; i <= columnCount; i++) {
				String columnName = metaData.getColumnLabel(i);
				if (StringUtils.equals(columnName, "password")) {
					continue;
				}
				String value = rs.getString(columnName);
				jsonObj.put(columnName, value);
			}
			array.add(jsonObj);
		}

		return array.toString();
	}

	/**
	 * 关闭jdbc连接对象
	 * 
	 * @param conn
	 * @param ps
	 * @param st
	 * @param rs
	 */
	public void close(Connection conn, PreparedStatement ps, Statement st, ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 获得连接数据库对象Connection
	 * 
	 * @param routeInfo
	 * @return
	 * @throws SQLException
	 */
	public Connection getConnection(RouteInfo routeInfo) throws SQLException {

		Connection conn = null;
		String ip = routeInfo.getIp();
		String port = String.valueOf(routeInfo.getPort());
		String dbname = routeInfo.getDbname();
		String driver = "com.mysql.jdbc.Driver"; // 获取mysql数据库的驱动类
		String url = "jdbc:mysql://" + ip + ":" + port + "/" + dbname; // 连接数据库（kucun是数据库名）
		String name = routeInfo.getUsername();// 连接mysql的用户名
		String pwd = routeInfo.getPassword();// 连接mysql的密码
		try {
			Class.forName(driver);
			DriverManager.setLoginTimeout(5);
			conn = DriverManager.getConnection(url, name, pwd);// 获取连接对象
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return conn;
	}
}
